package com.beiing.tianshuai.tianshuai.huodong;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.entity.ActiveInfoBean;
import com.beiing.tianshuai.tianshuai.entity.ActivitiesApplyForResultBean;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.huodong.presenter.ActivitiesApplyForPresenter;
import com.beiing.tianshuai.tianshuai.huodong.view.ActivitiesApplyForViewImpl;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.widget.CustomProgressDialog;
import com.tianshuai.easypopup.EasyPopup;

import java.text.MessageFormat;

import butterknife.BindView;
import me.shihao.library.XStatusBarHelper;

/**
 * 下单填写信息界面
 *
 * @author 刘泽启
 * @date 2017/8/7
 */

public class ActivitiesApplyForActivity extends BaseActivity
        implements ActivitiesApplyForViewImpl, View.OnClickListener {

    @BindView(R.id.ll_root_view)
    LinearLayout llRootView;
    @BindView(R.id.toolbar)
    Toolbar mToolBar;
    @BindView(R.id.toolbar_back)
    ImageButton toolbarBack;
    @BindView(R.id.huodong_sign_name)
    EditText mEtUserName;
    @BindView(R.id.huodong_sign_tel)
    EditText mEtUserTel;
    @BindView(R.id.tv_submit)
    TextView mTvSubmit;
    @BindView(R.id.tv_goods_amount)
    TextView tvGoodsAmount;
    @BindView(R.id.tv_total_price)
    TextView tvTotalPrice;

    private final String GOODS_TYPE_TICKET = "1";
    private final String GOODS_TYPE_OTHERS = "0";

    private static final String TAG = "ActivitiesApplyFor";

    /**
     * 是否为免费门票
     */
    private Boolean isFreeTicket;

    /**
     * 活动报名的presenter
     */
    private ActivitiesApplyForPresenter mPresenter;

    /**
     * 报名所购买的门票数量
     */
    private int mAmount;

    /**
     * 用户所报名的活动id
     */
    private String mAid;

    /**
     * 报名活动信息
     */
    private ActiveInfoBean mActiveInfoBean;

    /**
     * 支付弹窗
     */
    private EasyPopup mClearingPopup;

    /**
     * 活动报名提交界面
     *
     * @param context context
     * @param bean    活动信息
     */
    public static void start(Context context, ActiveInfoBean bean) {
        Intent intent = new Intent(context, ActivitiesApplyForActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("activeInfo", bean);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_huodong_sign_up;
    }

    @Override
    protected void init() {
        initStatusBar();
        initData();
        mPresenter = new ActivitiesApplyForPresenter(this);
        toolbarBack.setOnClickListener(this);
        mTvSubmit.setOnClickListener(this);
    }

    /**
     * 初始化状态栏
     */
    private void initStatusBar() {
        mToolBar.setPadding(0, XStatusBarHelper.getStatusBarHeight(mContext), 0, 0);
        XStatusBarHelper.immersiveStatusBar(this, 0);
    }

    private void initData() {

        //获取用户及活动的基本信息
        Intent intent = this.getIntent();
        mActiveInfoBean = (ActiveInfoBean) intent.getSerializableExtra("activeInfo");
        LogUtils.i("photo1", mActiveInfoBean.getCover());

        mAid = mActiveInfoBean.getAid();
        mAmount = mActiveInfoBean.getAmount();

        //设置用户姓名
        String userName = UserInfoBean.getNickName(mContext);
        mEtUserName.setText(userName);

        //设置用户电话号码
        mEtUserTel.setText(UserInfoBean.getUserTel(mContext));

        //设置门票数量
        tvGoodsAmount.setText(MessageFormat.format("{0}张", mAmount));

        //设置总价格
        float price = Float.valueOf(mActiveInfoBean.getPrice()) * mAmount;
        tvTotalPrice.setText(MessageFormat.format("共：{0}元", String.valueOf(price)));

        //判断商品是否为免费票务类
        isFreeTicket = TextUtils.equals(mActiveInfoBean.getPurchaseMethod(), GOODS_TYPE_TICKET)
                && price == 0;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.toolbar_back:
                finish();
                break;
            case R.id.tv_submit:
                String username = mEtUserName.getText().toString();
                String tel = mEtUserTel.getText().toString();
                if (TextUtils.isEmpty(username) || TextUtils.isEmpty(tel)) {
                    showShortText("输入内容不能为空");
                } else {
                    if (isFreeTicket) {
                        mPresenter.submitForFreeTicket(
                                UserInfoBean.getUid(mContext),
                                mAid,
                                String.valueOf(mAmount),
                                tel,
                                username
                        );
                    } else {
                        showShortText("暂不支持收费活动结算");
//                        if (TextUtils.equals(mActiveInfoBean.getPurchaseMethod(), GOODS_TYPE_TICKET)) {
//                            showClearingPopupWindow();
//                        }
                        // TODO: 2018/5/21 非票务类商品结算
                    }
                }
                break;
            default:
                break;
        }
    }

    /**
     * 显示结算方式选择弹窗
     * 如果弹窗没有被初始化先初始化
     * 初始化过之后不再初始化
     */
    private void showClearingPopupWindow() {
        if (mClearingPopup == null) {
            initClearingPopupWindow();
        }
        mClearingPopup.showAtLocation(getCurrentFocus(), Gravity.BOTTOM, 0, 0);
    }

    /**
     * 初始化结算方式选择弹窗
     */
    private void initClearingPopupWindow() {
        mClearingPopup = new EasyPopup(mContext);
        mClearingPopup.setContentView(R.layout.popwin_clearing_selector,
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT)
                .setAnimationStyle(R.style.AnimBottom)
                //是否允许点击PopupWindow之外的地方消失
                .setFocusAndOutsideEnable(true)
                //允许背景变暗
                .setBackgroundDimEnable(true)
                //变暗的透明度(0-1)，0为完全透明
                .setDimValue(0.4f)
                //变暗的背景颜色
                .setDimColor(Color.BLACK)
                //指定任意 ViewGroup 背景变暗
                .setDimView(llRootView)
                .createPopup();
    }

    @Override
    public void showProgress() {
        CustomProgressDialog.showLoading(mContext, "正在提交，请稍后", true);
    }

    @Override
    public void hideProgress() {
        CustomProgressDialog.stopLoading();
    }

    @Override
    public void onRequestSuccess(ActivitiesApplyForResultBean bean) {
        int code = bean.getCode();
        switch (code) {
            case 200:
                showShortText("报名成功");
                finish();
                break;
            case 401:
                showShortText("参数有误");
                break;
            case 402:
                showShortText("抱歉，来晚一步噢(> = <)");
                break;
            case 501:
                showShortText("每个手机号最多报名领取5张票");
                break;
            default:
        }
    }

    @Override
    public void onRequestFailed(Throwable throwable) {
        LogUtils.e(throwable, "报名请求异常", TAG);
        showShortText("请求失败");
    }
}
